//
//  CQAsyncDrawImage.swift
//  weibo
//
//  Created by chengqiang on 16/7/29.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit
import SDWebImage
class CQAsyncDrawImage: NSObject {
    static let sharAcyncDrawImage : CQAsyncDrawImage = CQAsyncDrawImage()
    //内存缓存
    private var imageCache : [String:UIImage] = [String:UIImage]()
    //异步绘制图片
    func AsncDrawImage(urlString:String,drawFinish:(image:UIImage) -> ()) {
        //先判断内存是否有图片
        if let image = imageCache[urlString]{
            drawFinish(image: image)
            return
        }
        
        SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: SDWebImageOptions(rawValue:0), progress: nil) { (image, error, _, _, _)->Void in
            if error != nil{
                let image = UIImage(named: "downloaderror")!
                //返回下载失败的图片
                dispatch_async(dispatch_get_main_queue(), {()->Void in
                    drawFinish(image: image)
                })
                return
            }
            
            //开启自县城一步绘制圆角图片
            dispatch_async(dispatch_get_global_queue(0, 0), { ()->Void in
                let size = image.size
                let rect = CGRect(origin: CGPointZero, size: size)
                //开启上下文
                UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.mainScreen().scale)
                //设置背景颜色
                UIColor.whiteColor().setFill()
                UIRectFill(rect)
                
                //圆角路径
                let path = UIBezierPath(ovalInRect: rect)
                //让元素在路径中
                path.addClip()
                
                //将图片画到矩形里面
                image.drawInRect(rect)
                //获取图片
                let newImage = UIGraphicsGetImageFromCurrentImageContext()
                //结束上下文
                UIGraphicsEndImageContext()
                //返回绘制好的图片
                dispatch_async(dispatch_get_main_queue(), { ()->Void in
                    self.imageCache[urlString] = newImage
                    drawFinish(image: newImage)
                })
            })
        }
    }
    
}
